import axios from 'axios'

import router from '@/router'

import { userStore } from '@/store/index'
import { menuStore } from '@/store/routesMenu.js'
import { clearLoginInfo } from '@/vueLsp/removeAll.js'
/**
 * 请求主地址配置
 * 引入loading
 * 设置请求地址
 */
import { baseUrl } from './baseUrl.js'
import { ElLoading, ElMessage } from 'element-plus'

const ElLoadingOptions = {
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)'
}

let loading = null
const BASEURL = baseUrl

// 正在更新token请求
let isRefreshToken = false
let requestList = []

// 创建请求实例
const service = axios.create({
    baseURL: BASEURL,
    timeout: 30000
})
service.defaults.withCredentials = false
// 添加请求拦截器（在发送请求之前做些什么）
service.interceptors.request.use(
    function (config) {
        // console.log('service.config', config)
        // 添加等待动画
        if (!loading) {
            loading = ElLoading.service(ElLoadingOptions)
        }
        // 添加头部信息
        const userState = userStore()
        if (userState.token) {
            config.headers.Authorization = userState.token
        }

        if (userState.userInfoData?.timestamp) {
            config.headers.timeStamp = userState.userInfoData?.timestamp
        }

        // 为每一个请求加上token
        if (config.params) {
            config.params.token = userState.token
        }

        if (config.body) {
            config.body.token = userState.token
        }

        config.headers['Content-Type'] = 'application/json'
        // console.log('====config', config)
        return config
    },
    function (error) {
        // 对请求错误做些什么
        if (loading) {
            loading.close()
        }
        return Promise.reject(error)
    }
)

// 添加响应拦截器(对响应数据做点什么)
service.interceptors.response.use(
    async function (response) {
        // console.log('===response===', response)
        // 关闭动画
        if (loading) {
            loading.close()
        }
        // 处理响应数据
        const res = response.data
        if (res.status == 200) {
            return res
        } else {
            const statusFlagFor401403 = [401, 403].includes(res?.status)
            if (statusFlagFor401403) {
                const promise = new Promise((resolve, reject) => {
                    requestList.push({ resolve, reject, config: response.config })
                })
                if (!isRefreshToken) {
                    isRefreshToken = true
                    const userState = userStore()
                    // 请求刷新新的token
                    const refreshRes = await userState.refreshTokenFun()
                    // console.log('====refreshRes', refreshRes)
                    if (refreshRes.status === 200) {
                        isRefreshToken = false
                        userState.token = refreshRes.data.shortToken
                        userState.refreshToken = refreshRes.data.longToken
                        userState.userInfoData = refreshRes.data
                        requestList.forEach((item) => {
                            // console.log('===item===', item)
                            service(item.config)
                                .then((res) => item.resolve(res))
                                .catch((err) => item.reject(err))
                        })
                        requestList = []
                    } else {
                        isRefreshToken = false
                        requestList = []
                        return Promise.reject(refreshRes)
                    }
                }
                return promise
            } else {
                const msgTip = res.message || '请求出错'
                ElMessage({
                    message: msgTip,
                    type: 'error'
                })
                const userState = userStore()
                const menuState = menuStore()
                userState.reset()
                menuState.reset()
                clearLoginInfo()
                router.push('/login')
                return Promise.reject(res)
            }
        }
    },
    function (error) {
        // console.log('===error===', error)
        // 对响应错误做点什么
        if (loading) {
            loading.close()
        }
        return Promise.reject(error)
    }
)
export default service
